iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 6
0

目標

今天要做的是動態顯示查詢結果,如下圖所示,當輸入查詢字串時,顯示符合條件的字串並highlight
https://ithelp.ithome.com.tw/upload/images/20200912/20121041hslPR8S4Jr.png

Step1

透過fetch()取得資料

const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';

const cities = [];

fetch(endpoint)
    .then(blob => blob.json())
    .then(data => cities.push(...data))

fetch() 會回傳 promise 物件

將promise物件解析後,以展開運算符(Spread Operator)將資料分別傳入陣列

Step2

輸入文字處理

function findMatches(wordToMatch, cities) {
    return cities.filter(place => {
        // 將文字轉換成正規表達式
        const regex = new RegExp(wordToMatch, 'gi');
        return place.city.match(regex) || place.state.match(regex);
    });
}

function displayMatches() {
    console.log(this.value);
    const matchArray = findMatches(this.value, cities);
    console.log(matchArray);
}

const searchInput = document.querySelector('.search');
const suggestion = document.querySelector('.suggestions');

searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);

new RegExp(wordToMatch, 'gi'); 建構子函式 正則表達式標誌

正則表達式標誌

Step3

顯示查詢結果

function displayMatches() {
    // console.log(this.value);
    const matchArray = findMatches(this.value, cities);
    // console.log(matchArray);
    const html = matchArray.map(place => {
        const regex = new RegExp(this.value, 'gi');
        return `
            <li>
                <span class="name">${place.city}, ${place.state}</span>
                <span class="population">${place.population}</span>
            </li>
        `
    }).join('');
    suggestions.innerHTML = html;
}

Step4

美化顯示

//數字加上逗號
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

function displayMatches() {
    // console.log(this.value);
    const matchArray = findMatches(this.value, cities);
    // console.log(matchArray);
    const html = matchArray.map(place => {
        const regex = new RegExp(this.value, 'gi');
        const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
        const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
        return `
            <li>
                <span class="name">${cityName}, ${stateName}</span>
                <span class="population">${numberWithCommas(place.population)}</span>
            </li>
        `
    }).join('');
    suggestions.innerHTML = html;
}

上一篇
Day05 -- Flex Panels Image Gallery
下一篇
Day07 -- Array Cardio Day 2
系列文
森林系工程師之開始工作才學JS?!32
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言